<?php

namespace App\Imports;

use App\Models\User\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DemoImport extends CommonImport
{
    public function __construct(array $params=[]) {
        $this->params = $params;
        $this->instance = new User();
    }

    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection) {

        $collection = $collection->filter()->values();
        $this->count = $collection->count();
        if($this->count<=0)return true;
        $time = date('Y-m-d H:i:s');

        $records = [];
        foreach ($collection as $k=>$v) {
            if($k<=0)continue;//过滤表头
            $v = $v->toArray();
            if(count(array_filter($v))<=0){continue;}

            //组装数据
            $records[] = [
                'name'=>$v[0],
                'passport'=>$v[1],
                'phone'=>$v[2],
                'birthday'=>$this->transformDateTime($v[3],'Y-m-d'),
                'point'=>$v[4],
                'beizhu'=>$v[5],
                'created_at'=>$time,
                'updated_at'=>$time
            ];

            $this->countSuccess++;
        }

        $passports = array_column($records, 'passport');

        if(count(array_unique($passports))!=count($passports)){
            $this->success = false;
            $this->msg = '有重复项，请检查数据！';
            return false;
        }
        try{
            DB::beginTransaction();

            if(count($records)>0)
                $this->instance->insert($records);

            DB::commit();
            $this->msg = "本次导入共：".$this->count.'条数据，成功：'.$this->countSuccess.'条，失败：'.$this->countFail.'条';
            return true;
        }catch(\Exception $e){
            DB::rollback();
            $this->success = false;
            $this->msg = $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return false;
        }



    }
}
